from fetchemApp.models import *
import xlwt
import datetime
from django.conf import settings
import os

############################
def func(sub):
    #"This function computes the marks obtained in an assignment by a student"
    Total=0
    QuesList=sub.questiongrade_set.all();
    for x in QuesList:
                t = x.question.ParentQuestion
                while t:
                    t = t.ParentQuestion
                Total += x.Marks
    return Total


def createSheet(courseObj):
    #create workbook
    wbk=xlwt.Workbook(encoding="utf-8")
    
    #Add a sheet to the workbook
    sheet=wbk.add_sheet('sheet 1',cell_overwrite_ok=True)
    #Creating the attributes for the sheet
    sheet.write(0,0,'Roll No.')
    sheet.write(0,1,'Name')

    print courseObj.CourseNo
    StudentObjList= courseObj.Students.all()
    NoStudents=StudentObjList.count()
    #print "The number of students enrolled in this course are:",NoStudents 
    #Get Assignment
    AssignmentObjList=Assignment.objects.filter(course=courseObj)
    print AssignmentObjList 
    
    count=0
    try:
        for a in AssignmentObjList: # for every assignment 
            sheet.write(0,count+2,a.SubjectLine)
            StudentList=[]
            for s in courseObj.Students.all():
                    if (Submission.objects.filter(assignment=a,student=s,Status="Graded") or Submission.objects.filter(assignment=a,student=s,Status="Sent")):
                        StudentList+= [s]
            print StudentList
            #StudentList is the list of students who have submitted the assignment
            MarksList={}
            for stu in StudentObjList:
                if stu in StudentList:
                    print Submission.objects.filter(assignment=a,student=stu)
                    MarksList[stu.RollNo]=func(Submission.objects.filter(assignment=a,student=stu)[0])
                else:
                    MarksList[stu.RollNo] = 0;  
            
            print MarksList
            d={}
            for j in range (0,NoStudents):
                d[j+1]= [StudentObjList[j].Name,StudentObjList[j].RollNo]
                #print "the list of students in this course is:"
                #print d[j+1][0]
                sheet.write(j+1,0,d[j+1][1])
                sheet.write(j+1,1,d[j+1][0])
                sheet.write(j+1,count+2,MarksList[StudentObjList[j].RollNo])
            count +=1
    except IndexError:
        print "Error: No student has submitted this assignment"
        #wbk.save(excel)
    path = os.path.join(settings.MEDIA_ROOT, ('Excel Files/' + str(courseObj.CourseNo) + ' ' + str(datetime.datetime.now())))
    wbk.save(path + '.xls')
    